package cn.redragon.soa.common.util;

import cn.redragon.soa.common.constant.AuthConstant;
import cn.redragon.soa.common.constant.Constants;
import java.util.Optional;
import lombok.AccessLevel;
import lombok.NoArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.util.Base64Utils;

@NoArgsConstructor(access = AccessLevel.PRIVATE)
public class PasswordUtil {

    public static Optional<String> decodeBasicAuthPassword(String authHeader, PasswordEncoder encoder) {
        if (StringUtils.isBlank(authHeader)) {
            return Optional.empty();
        }

        if (!authHeader.startsWith(AuthConstant.BASIC_AUTH_PREFIX)) {

            return Optional.empty();
        }

        String authStr = decodeAuthHeader(authHeader);

        String pwd = authStr.contains(Constants.Separator.COLON) ?
            authStr.split(Constants.Separator.COLON)[1] : authStr;

        return Optional.ofNullable(pwd).map(encoder::encode);
    }

    public static String encodeBasicAuth(String username, String password) {
        return AuthConstant.BASIC_AUTH_PREFIX.concat(Base64Utils.encodeToString(username.concat(Constants.Separator.COLON).concat(password).getBytes()));
    }

    private static String decodeAuthHeader(final String authHeader) {
        return new String(Base64Utils.decodeFromString(authHeader.replace(AuthConstant.BASIC_AUTH_PREFIX, StringUtils.EMPTY).trim()));
    }

}
